package com.example.browser;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class moveselect extends AppCompatActivity {
    private ArrayList arrayList=new ArrayList();
    private ListView folder_list;
    private MyDatabaseHelper dbHelper;
    private String gtitle,gurl,gid;
    private String get_title,get_url,foldername;//暂存从数据库得到的title和url
    private int get_id; //暂存从数据库得到的id
    private boolean if_exist;
    private String titler, url;//按值查找详细信息
    int id; //按值查找id
    private TextView text_title, text_url;//书签详细信息edittext
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_moveselect);
        folder_list=(ListView)findViewById(R.id.folder_list);
        Intent intent=super.getIntent();
        gid=intent.getStringExtra("id");
        gtitle=intent.getStringExtra("title");
        gurl=intent.getStringExtra("url");
        queryfolder();
        //点击函数：
        folder_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (if_exist) {

                    selectfoldder(position,gtitle,gurl,folderquery_by_id2(position));
                    int resultid=Integer.parseInt(gid);
                    deleteid(resultid);
                    finish();
                }


            }
        });
    }
    //数据库逆序查询函数：
    public void queryfolder(){
        final ArrayList<HashMap<String, Object>> listItem2 = new ArrayList <HashMap<String,Object>>();/*在数组中存放数据*/
        //第二个参数是数据库名
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //Cursor cursor = db.rawQuery("select * from bookmarkDB", null);
        //查询语句也可以这样写
        Cursor cursor = db.query("addfolderDB", null, null, null, null, null, "id desc");
        if (cursor != null && cursor.getCount() > 0) {
            if_exist=true;
            while(cursor.moveToNext()) {
                get_id=cursor.getInt(0);//得到int型的自增变量
                get_title = cursor.getString(1);

                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("foldername", get_title);
                map.put("folderpic", String.valueOf(R.drawable.folder));
                arrayList.add(get_id);
                listItem2.add(map);
                //new String  数据来源， new int 数据到哪去
                SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem2,R.layout.folderzujian,
                        new String[] {"foldername","folderpic"},
                        new int[] {R.id.foldername,R.id.folderpic});
                folder_list.setAdapter(mSimpleAdapter);//为ListView绑定适配器
            }
        }else {
            if_exist=false;
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("foldername", "还没有分组哦");
            map.put("folderpic", "");
            arrayList.add(get_id);
            listItem2.add(map);
            //new String  数据来源， new int 数据到哪去
            SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem2,R.layout.folderzujian,
                    new String[] {"foldername","folderpic"},
                    new int[] {R.id.foldername,R.id.folderpic});
            folder_list.setAdapter(mSimpleAdapter);//为ListView绑定适配器
        }


        cursor.close();
        db.close();
    }
    public String folderquery_by_id2(int position){
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from addfolderDB", null);
        while (cursor.moveToNext()) {
            url=cursor.getString(2);
            titler=cursor.getString(1);
            id=cursor.getInt(0);
            //找到id相等的就返回url
            if (arrayList.get(position).equals(id))
                break;
        }
        cursor.close();
        db.close();
        return url;
    }

    //查询数据库里的字段
    public void selectfoldder(int position,String title,String url,String foldername) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        //String sql ="SELECT * FROM " + TABLENAME + " WHERE name='"+username+"'AND birthday='"+birthday+"'";
        //String sql = "select * from " + TABLENAME + " where name like '%"+ username + "%'";
        String sql ="SELECT * FROM "+foldername+" WHERE url='"+url+"'";

        Cursor result=db.rawQuery(sql, null);//用Cursor对象获得执行查询结果集
        if(result.moveToFirst())//如果结果集的第一行有数据
        {
            //https://codingdict.com/questions/117721
            //Toast.makeText(WebView.this,result.getString(1), Toast.LENGTH_SHORT).show();
            Toast.makeText(moveselect.this, result.getString(1)+"已存在", Toast.LENGTH_LONG)
                    .show();
            result.close();
            db.close();

        }
        else {
            addfolder(position,title,url);
            result.close();
            db.close();

        }


    }
    //数据库添加数据(文件夹表)
    public void addfolder(int position,String title,String url){
        //第二个参数是数据库名
        MyDatabaseHelper  dbHelper = new MyDatabaseHelper(moveselect.this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("title",title);
        values.put("url", url);
        //insert（）方法中第一个参数是表名，第二个参数是表示给表中未指定数据的自动赋值为NULL。第三个参数是一个ContentValues对象
        db.insert(folderquery_by_id2(position),null,values);
        Toast.makeText(moveselect.this,"添加成功",Toast.LENGTH_SHORT).show();
        arrayList.clear();
        //刷新UI
        queryfolder();
    }
    //
    public void deleteid(int id) {
        dbHelper = new MyDatabaseHelper(this,"dmbrowser.db",null,1);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        String sql = "delete from bookmarkDB where id=" + id;
        db.execSQL(sql);
        db.close();


    }

}